const path = require("path");
const fse = require("fs-extra");
const joinPackagejson = (str, projectCode) => {
  // 验证 projectCode 是否合法
  const PROJECT_CODE_REGEX = /^[a-zA-Z0-9]+$/;
  if (!PROJECT_CODE_REGEX.test(projectCode)) {
    console.error("Invalid project code");
    return;
  }

  try {
    // 匹配注释中的依赖项信息
    const MODULE_REGEX = /\/\*\{Node_modules=[a-zA-Z0-9^.]+\}\*\//gim;
    const matchedModules = str.match(MODULE_REGEX);
    if (!matchedModules || !matchedModules.length) {
      console.log("No match found in the input string");
      return;
    }

    let moduleString = matchedModules[0].replace(/[\/*{}]/gi, "");
    moduleString = moduleString.split("=")[1];
    const parsedDependencies = {};
    moduleString.split(",").forEach((dep) => {
      const [dependencyName, version] = dep.split("^");
      parsedDependencies[dependencyName] = version;
    });

    const packageJsonPath = path.join(
      __dirname,
      "../../projects",
      projectCode,
      "package.json"
    );

    let packageJson = fse.readFileSync(packageJsonPath, "utf8");
    packageJson = JSON.parse(packageJson);

    let needUpdate = false;

    Object.keys(parsedDependencies).forEach((dependencyName) => {
      if (
        !packageJson.dependencies ||
        !packageJson.dependencies[dependencyName]
      ) {
        packageJson.dependencies[dependencyName] =
          "^" + parsedDependencies[dependencyName];
        needUpdate = true;
      } else if (
        packageJson.dependencies[dependencyName].replace(/^[\^~]/, "") !==
        parsedDependencies[dependencyName]
      ) {
        packageJson.dependencies[dependencyName] =
          "^" + parsedDependencies[dependencyName];
        needUpdate = true;
      }
    });

    if (needUpdate) {
      fse.outputFileSync(
        packageJsonPath,
        JSON.stringify(packageJson, null, 2),
        "utf8"
      );
    }
  } catch (error) {
    console.error("An error occurred:", error.message);
  }
};

module.exports = joinPackagejson